/*
 * MemBuff.cpp
 *
 *  Created on: Feb 8, 2013
 *      Author: ozma
 *
 *  Don't malloc or new use on stack MemBuff
 *  assignment and copy constructor copy all for you
 *  !! do not pass the internal buffer. instead pass the MemBuff by reference. if you must pass the internal buffer, make sure you remain in the MemBuff scope !!
 *  MemBuff with auto pointer does not make sense pick one.
 */

#include "MemBuff.h"
#include <string.h>

static const char* EMPTY_STR = "";

MemBuff::MemBuff() {
	init(EMPTY_STR, 0);
}

MemBuff::MemBuff(const MemBuff & other) {
	init(other.buf, other.size);
}

MemBuff::MemBuff(std::string str) {
	init(str.c_str(), str.length());
}

MemBuff::MemBuff(const char* buf, int size) {
	init(buf, size);
}

void MemBuff::deleteInternals(){
	delete [] buf;
	buf = NULL;
}

MemBuff::~MemBuff() {
	deleteInternals();
}

void MemBuff::init(const char* buf, int size){
	this->buf = new char[size+1];
	memcpy(this->buf, buf, size);
	this->buf[size] = '\0';
	this->size = size;
}

MemBuff & MemBuff::operator=(const MemBuff & other){
	if ( this == &other )
		return *this;
	deleteInternals();
	init(other.buf, other.size);
	return *this;
}

bool MemBuff::operator==(const MemBuff & other){
	if (other.size != size)
		return false;
	return ! memcmp(buf, other.buf, size);
}


